import axios from 'axios';
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user.js'

//1. 创建axios对象
const service = axios.create();

//2. 请求拦截器
service.interceptors.request.use(config => {
  const userStore = useUserStore()
  let token = userStore.token
  if (token) {
    config.headers['Authorization'] = token
  }
  return config;
}, error => {
  Promise.reject(error);
});

//3. 响应拦截器
service.interceptors.response.use(response => {
  const { data } = response
  if (response.config.url.indexOf('downloadAttachment') > -1||response.config.url.indexOf('queryOrder') > -1) {
    return response
  } else if (data.meta.code == 200 || data.meta.code === '10006') {
    return data
  }
  else {
    ElMessage.error(data.meta.msg)
    return Promise.reject(new Error(data.meta.msg));
  }
}, error => {
  if (error.response.status == 500) {
    ElMessage.error('服务器错误500')
  }
  return Promise.reject(error);
});

export default service;